//
//  RootViewController.m
//  Alfresco
//
//  Created by Michael Muller on 9/1/09.
//  Copyright Zia Consulting 2010.  Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
//

#import "RootViewController.h"
#import "RepositoryNodeViewController.h"
#import "Site.h"
#import "RepositoryItem.h"
#import "RepositoryItemTableViewCell.h"
#import "Utility.h"
#import "DocumentViewController.h"

@implementation RootViewController

@synthesize siteInfo;
@synthesize companyHomeItems;
@synthesize siteDownloader;
@synthesize itemDownloader;
@synthesize companyHomeDownloader;
@synthesize serviceInfoDownloader;
@synthesize progressBar;

- (void)dealloc {
	[siteInfo release];
	[companyHomeItems release];
	[siteDownloader release];
	[itemDownloader release];
	[companyHomeDownloader release];
	[serviceInfoDownloader release];
	[progressBar release];
    [super dealloc];
}

- (void)viewDidLoad {

	// start loading the list of sites
	SiteListDownload *down = [[SiteListDownload alloc] initWithDelegate:self];
	self.siteDownloader = down;
	[down start];
	[down release];
	
	if (userPrefShowCompanyHome()) {
		// start loading basic info about the repository (so we can find the root folder)
		ServiceInfoDownload *down2 = [(ServiceInfoDownload*)[ServiceInfoDownload alloc] initWithDelegate:self];
		self.serviceInfoDownloader = down2;
		[down2 start];
		[down2 release];
	}
	
    [super viewDidLoad];
}

- (void) asyncDownloadDidComplete:(AsynchonousDownload *)async {
	
	// if we're being notified that a list of sites is ready
	if ([async isKindOfClass:[SiteListDownload class]]) {
		self.siteInfo = self.siteDownloader.siteList;
		[(UITableView *) self.view reloadData];
	}
	
	// if we're being told that the service info is ready
	if ([async isKindOfClass:[ServiceInfoDownload class]]) {
		NSString *folder = [(ServiceInfoDownload *)async rootFolder];
		NSLog(@"root folder: %@", folder);
		
		// find the items in the "Company Home" folder
		FolderItemsDownload *down = [FolderItemsDownload alloc];
		[down initWithURL:[NSURL URLWithString:folder] delegate:self];
		self.companyHomeDownloader = down;
		down.context = @"companyHome";
		down.parentTitle = @"Top";
		[down start];
		[down release];
	}
	
	// if we're being told that a list of folder items is ready
	if ([async isKindOfClass:[FolderItemsDownload class]]) {
		
		FolderItemsDownload *fid = (FolderItemsDownload *) async;
		
		// if we got back a list of top-level items, find the document library item
		if ([fid.context isEqualToString:@"topLevel"]) {
			for (RepositoryItem *item in self.itemDownloader.children) {
				if ([item.title isEqualToString:@"documentLibrary"]) {
					
					// this item is the doc library; find its children
					FolderItemsDownload *down = [[FolderItemsDownload alloc] initWithGUID:item.guid delegate:self];
					self.itemDownloader = down;
					down.parentTitle = fid.parentTitle;
					[down start];
					[down release];
					break;
				}
			}
		}
		
		// did we get back the items in "company home"?
		else if ([fid.context isEqualToString:@"companyHome"]) {
			self.companyHomeItems = self.companyHomeDownloader.children;
			[(UITableView *) self.view reloadData];
		}
		
		// if it's not a list of top-level items, it's the items in the doc library
		else {
			// create a new view controller for the list of repository items (documents and folders)
			RepositoryNodeViewController *vc = [[RepositoryNodeViewController alloc] initWithNibName:nil bundle:nil];
			
			vc.title = fid.parentTitle;
			vc.children = fid.children;
			
			// push that view onto the nav controller's stack
			[self.navigationController pushViewController:vc animated:YES];
			[vc release];
		}
	}
}

- (void) asyncDownload:(AsynchonousDownload *)async didFailWithError:(NSError *)error {
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
	[siteInfo release];
}

#pragma mark Table view methods

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	return (section == 1) ? @"Company Home" : @"Sites";
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return userPrefShowCompanyHome() ? 2 : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (section == 1) ? [companyHomeItems count] : [siteInfo count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([indexPath section] == 1) {
		RepositoryItemTableViewCell *cell = (RepositoryItemTableViewCell *) [tableView dequeueReusableCellWithIdentifier:RepositoryItemCellIdentifier];
		if (cell == nil) {
			NSArray *nibItems = [[NSBundle mainBundle] loadNibNamed:@"RepositoryItemTableViewCell" owner:self options:nil];
			cell = [nibItems objectAtIndex:0];
			NSAssert(nibItems, @"Failed to load object from NIB");
		}
		
		RepositoryItem *child = [self.companyHomeItems objectAtIndex:[indexPath row]];
		
		cell.filename.text = child.title;
		cell.details.text = [[NSString alloc] initWithFormat:@"%@ %@", child.lastModifiedBy, child.lastModifiedDate];
		if ([child isFolder]) {
			UIImage * img = [UIImage imageNamed:@"folder.png"];
			cell.imageView.image  = img;
		}
		else {
			cell.imageView.image = imageForFilename(child.title);
		}
		
		cell.accessoryType = [child isFolder] ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
		
		return cell;
	}
	else {
		static NSString *CellIdentifier = @"Cell";
		
		UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		}
		
		NSArray *collection = ([indexPath section] == 1) ? self.companyHomeItems : self.siteInfo;
		cell.textLabel.text = [[collection objectAtIndex:[indexPath row]] title];
		cell.imageView.image = [UIImage imageNamed:@"folder.png"];

		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		
		return cell;
	}
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	[self.siteDownloader.urlConnection cancel];
	[self.itemDownloader.urlConnection cancel];
	[self.companyHomeDownloader.urlConnection cancel];
	[self.serviceInfoDownloader.urlConnection cancel];
	
	if ([indexPath section] == 1) {
		// get the document/folder information associated with this row
		RepositoryItem *item = [self.companyHomeItems objectAtIndex:[indexPath row]];
		
		if ([item isFolder]) {
			FolderItemsDownload *down = [[FolderItemsDownload alloc] initWithGUID:item.guid delegate:self];
			down.context = @"companyHomeItems";
			down.parentTitle = item.title;
			self.itemDownloader = down;
			[down start];
			[down release];
		}
		else {
			self.progressBar = [DownloadProgressBar createAndStartWithURL:[NSURL URLWithString:item.contentLocation] delegate:self message:@"Downloading Document" filename:item.title];
		}
	}
	else {
		// get the site information associated with this row
		Site *s = [self.siteInfo objectAtIndex:[indexPath row]];
		
		// start loading the list of top-level items for this site
		FolderItemsDownload *down = [[FolderItemsDownload alloc] initWithNode:s.node delegate:self];
		down.context = @"topLevel";
		down.parentTitle = s.title;
		self.itemDownloader = down;
		[down start];
		[down release];
	}
}

- (void) download:(DownloadProgressBar *)down completeWithData:(NSData *)data {
	
	DocumentViewController *doc = [[DocumentViewController alloc] initWithNibName:@"DocumentViewController" bundle:[NSBundle mainBundle]];
	
	doc.fileData = data;
	doc.fileName = down.filename;
	
	doc.hidesBottomBarWhenPushed = YES;
	
	[self.navigationController pushViewController:doc animated:YES];
	
	[doc release];
}

@end
